##获取 Microsoft OAuth2 访问令牌##
import re
import time
from datetime import datetime, timedelta

import pytz
import requests


def get_access_token(client_id, refresh_token):
    data = {
        'client_id': client_id,
        'grant_type': 'refresh_token',
        'refresh_token': refresh_token
    }
    response = requests.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', data=data)
    return response.json()['access_token']


##连接 IMAP 服务器##
import imaplib


def connect_imap(email, access_token):
    # 生成认证字符串
    auth_string = f"user={email}\1auth=Bearer {access_token}\1\1"

    # 连接到IMAP服务器
    mail = imaplib.IMAP4_SSL('outlook.office365.com')
    mail.authenticate('XOAUTH2', lambda x: auth_string)

    return mail


##获取邮件内容##
from email import message_from_bytes
from email.header import decode_header


def get_ins_code(mail):
    # 选择收件箱
    mail.select("INBOX")

    # 搜索邮件
    # criteria = '(FROM "@mail.instagram.com")'

    # 搜索条件：来自Instagram官方的邮件，并且时间在15分钟以内
    current_time = datetime.now(pytz.utc)
    time_threshold = current_time - timedelta(minutes=15)
    criteria = f'(FROM "mail.instagram.com" SINCE "{time_threshold.strftime("%d-%b-%Y")}")'

    # 取全部邮件
    # criteria = 'ALL'

    status, messages = mail.search(None, criteria)

    # 获取最新的10封邮件
    for num in messages[0].split()[-10:]:
        status, msg_data = mail.fetch(num, '(RFC822)')
        email_message = message_from_bytes(msg_data[0][1])

        # 获取邮件基本信息
        sender = decode_header(email_message['from'])[0][0]
        print("---------------------------------------------------------------------------------------------------------------")
        print(f"发件人: {sender}")
        body = ''
        # 获取邮件正文
        if email_message.is_multipart():
            for part in email_message.walk():
                content_type = part.get_content_type()
                content_disposition = str(part.get('Content-Disposition'))

                # 提取正文内容
                if content_type == "text/plain" and "attachment" not in content_disposition:
                    body = part.get_payload(decode=True).decode()
                    break
        else:
            body = email_message.get_payload(decode=True).decode()
        print(f"正文: {body}")
        parts = re.split(r'[<>"\s]', body)
        for part in parts:
            if len(part) == 6 and part.isdigit():
                return part
    return ''

def request_ins_email_code(email_address, client_id, refresh_token):
    # 获取访问令牌
    access_token = get_access_token(client_id, refresh_token)
    # 连接到IMAP服务器
    mail = connect_imap(email_address, access_token)
    # 获取邮件内容
    code = get_ins_code(mail)
    print("获取到验证码：", code)
    # 关闭连接
    mail.logout()
    return code


if __name__ == '__main__':
    startTime = time.time()
    # client_id = "9e5f94bc-e8a4-4e73-b8be-63364c29d753"  # 客户端ID
    # refresh_token = "M.C531_BAY.0.U.-CiYRM*AjIzlUhHwP6pCJAihW5Hc9tMLh8aiv0mYOLqgbDSXu9DZUnY60Zgi0EREu76O99CHjmuKOkVekDmgiz9xY7u0Q0!N8ockSu5jF8W8OXFTDG8Z1!nKxC1V9yErM0c5XyQdX488CLwLxSg1Ls5K7Dk4MW7JMvEvoCWLO28TtobZJ9eiwllbT2BqY7DExAfYZNK5QeyEOcHE8rWhsaLGeTU8MEmBWUDZGfPLtavn*h2JUAwGeHCHeaypH5qPLUvtKe0mZXRq3JiCu!T4m*Dxvgr5fXIhy1ZUl4AqQ1HG8vzI5i8h6yYKGJuh2gKkdq4WdClTCmWSRV9l!WM78fLSz01HnXGv9VFFey3G5i3CB1DdQnZNjiSers9RDb7mecPdBKXxb4IX6i1M7ZrT40LSHdgvP*oaUxIhFSWWrpvBP"  # 替换为你的刷新令牌
    # email_address = "ambrakedahyi@outlook.com"  # 替换为你的邮箱地址

    client_id = "9e5f94bc-e8a4-4e73-b8be-63364c29d753"  # 客户端ID
    refresh_token = "M.C556_BAY.0.U.-CvhDeGWtU2TzoOKRvVkdH2ZP*beIxHTRcmI4eHV*AoW9!TQNZz7fxvsZ7FCKZG9qxY98nDRH8o20VoObACKfG3O7*J72s1bhetPalO3p0GWOEHoyDrIWAPbqSCcYB4QEs9YOf5PO2CWC8jcOb4!aQ!SmOylJ7j7EI7ZEk0dDSbjqRfgIHdClo3!qOGCbUUm8TaV9ajKNCvNN9qoW7tNUMx9SZ8714ho5x3StOQM13PVFMSznwXeQYNB6WY4V7LuEVxQ!9BcEM51XukvqEOGfqwoev7rjORu8nDVqnd2Hg1iuMU7I*GiJi93hyeR29Ud0CT7lD1tNWD1BkaeOFcsIa*cxJiDLRMVwGkWx6shhacluuoc!5pkIneM9bJAm2Jor6bLfyCEaVWdWiVm2Z!onBGgtCk*veinhP!9DcDyltztO"  # 替换为你的刷新令牌
    email_address = "jtaqwjh@hotmail.com"  # 替换为你的邮箱地址

    # 获取访问令牌
    access_token = get_access_token(client_id, refresh_token)
    print('即将连接IMAP服务器')
    # 连接到IMAP服务器
    mail = connect_imap(email_address, access_token)
    print('连接IMAP服务器完成')
    # 获取邮件内容
    code = get_ins_code(mail)
    print("验证码：", code)
    print("程序运行时间：", time.time() - startTime)

    # 关闭连接
    mail.logout()